package com.zhejiangzhengyuan.municipal_common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhejiangzhengyuan.municipal_common.entity.*;
import com.zhejiangzhengyuan.municipal_common.entity.dto.SubjectDto;
import com.zhejiangzhengyuan.municipal_common.entity.vo.SubjectVo;
import com.zhejiangzhengyuan.municipal_common.mapper.*;
import com.zhejiangzhengyuan.municipal_common.response.ResponseVo;
import com.zhejiangzhengyuan.municipal_common.service.SubjectService;
import com.zhejiangzhengyuan.municipal_common.utils.ConstantUtil;
import com.zhejiangzhengyuan.municipal_common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

import static com.zhejiangzhengyuan.municipal_common.utils.DateFormatUtil.timeFormat;
import static com.zhejiangzhengyuan.municipal_common.utils.JwtUtil.HEADER_STRING;
import static com.zhejiangzhengyuan.municipal_common.utils.JwtUtil.parseJWT;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 权限模块中的认证主体表，与业务系统中的用户数据一一对应，存储用户的用户名、密码、权限关系起点。单独存储是为了将权限和业务解耦 服务实现类
 *
 * @author linju
 * @since 2019-11-22
 */
@Service
@Transactional
@Slf4j
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject>
    implements SubjectService {

  @Autowired private SubjectMapper subjectMapper;
  @Autowired private BCryptPasswordEncoder encoder;
  @Autowired private HttpServletRequest request;
  @Autowired private DepartmentMapper departmentMapper;
  @Autowired private RoleMapper roleMapper;
  @Autowired private UserInfoMapper userInfoMapper;
  @Autowired private DepartmentUserInfoMappingMapper departmentUserInfoMappingMapper;
  @Autowired private SubjectRoleMappingMapper subjectRoleMappingMapper;
  @Autowired private SubjectUserInfoMappingMapper subjectUserInfoMappingMapper;

  @Override
  public ResponseVo findById(Long id) {
    Subject subject = subjectMapper.selectById(id);
    return subject == null
        ? ResponseVo.NOT_FOUND_RESOURCES
        : new ResponseVo<>(ConstantUtil.ResultCode.SUCCESS, subject);
  }

  public ResponseVo findByName(String name) {
    Subject subject = subjectMapper.findByName(name);
    return subject == null
        ? ResponseVo.NOT_FOUND_RESOURCES
        : new ResponseVo<>(ConstantUtil.ResultCode.SUCCESS, subject);
  }

  // 登录校验
  public Subject login(String username, String password) {
    Subject subject = subjectMapper.findByName(username);
    return subject != null && encoder.matches(password, subject.getPassword()) ? subject : null;
  }

  // 冻结账号
  public void freeze(Integer id) {
    Claims claims = parseJWT((String) request.getAttribute("id"));
    Subject subject = subjectMapper.selectById(id);
    subject.setUpdateTime(timeFormat(System.currentTimeMillis()));
    subject.setEnabled(false);
    subjectMapper.update(subject, null);
  }

  @Override
  public Page<SubjectVo> FuzzyUserInfoByRoleIdAndUserName(
      String subject, String role, Page<SubjectVo> subjectVoPage) {

    Page<SubjectVo> subjectVoPage1 = subjectMapper.selectAllFuzzy(subjectVoPage, subject, role);
    List<SubjectVo> subjectVoList = subjectVoPage1.getRecords();
    for (SubjectVo subjectVo : subjectVoList) {
      subjectVo.setDepartmentNames(
          departmentMapper.selectDepartmentListByUserId(subjectVo.getId()));
      subjectVo.setRoleNames(roleMapper.selectRoleNameListByUserId(subjectVo.getId()));
    }
    return subjectVoPage1;
  }

  // 查询
  @Override
  public Page<SubjectVo> selectAllUserInfo(Page<SubjectVo> subjectVoPage) {
    Page<SubjectVo> subjectPage = subjectMapper.selectAllUserInfo(subjectVoPage);
    List<SubjectVo> subjectVoList = subjectPage.getRecords();
    for (SubjectVo subjectVo : subjectVoList) {
      List<String> strings = departmentMapper.selectDepartmentListByUserId(subjectVo.getId());
      subjectVo.setDepartmentNames(strings);
      subjectVo.setRoleNames(roleMapper.selectRoleNameListByUserId(subjectVo.getId()));
    }
    return subjectPage;
  }
  // 新建
  @Override
  public boolean insertUserInfo(SubjectDto dto) {
    String password = encoder.encode(dto.getPassWord());
    log.info(password);
    Subject subject = new Subject();
    subject.setPassword(password);
    String passwordString = password.substring(6);
    String substring = passwordString.substring(0, 21);

    subject.setSalt(substring);
    //        subject.setSalt(password.substring(6).substring(0,
    // password.substring(6).indexOf(".")));
    subject.setSubjectName(dto.getSubjectName());
    subject.setEnabled(true);
    subject.setCreateTime(timeFormat(System.currentTimeMillis()));
    subject.setUpdateTime(timeFormat(System.currentTimeMillis()));
    // 认证主体及关联表添加
    if (subjectMapper.insert(subject) > 0) {
      // 从前端取出字符串转id数组
      if (dto.getRoleNameIds() != null) {
        String roleNameIds = dto.getRoleNameIds();
        String[] roleSplit = roleNameIds.split(",");
        for (String s : roleSplit) {
          SubjectRoleMapping subjectRoleMapping = new SubjectRoleMapping();
          subjectRoleMapping.setRoleId(Long.parseLong(s));
          subjectRoleMapping.setSubjectId(subject.getId());
          subjectRoleMappingMapper.insert(subjectRoleMapping);
        }
      } else {
        return false;
      }

      UserInfo userInfo =
          new UserInfo()
              .setUsername(dto.getUsername())
              .setGender(dto.getGender())
              .setWordNum(dto.getWordNum())
              .setPosition(dto.getPosition())
              .setRemark(dto.getRemark())
              .setPhoneNum(dto.getPhoneNum());
      if (userInfoMapper.insert(userInfo) > 0) {
        SubjectUserInfoMapping subjectUserInfoMapping = new SubjectUserInfoMapping();
        subjectUserInfoMapping.setSubjectId(subject.getId());
        subjectUserInfoMapping.setUserInfoId(userInfo.getId());
        subjectUserInfoMappingMapper.insert(subjectUserInfoMapping);
        String departmentIds = dto.getDepartmentIds();
        String[] split = departmentIds.split(",");
        for (String s : split) {
          DepartmentUserInfoMapping departmentUserInfoMapping = new DepartmentUserInfoMapping();
          departmentUserInfoMapping.setUserInfoId(userInfo.getId());
          departmentUserInfoMapping.setDepartmentId(Long.parseLong(s));
          departmentUserInfoMappingMapper.insert(departmentUserInfoMapping);
        }
        return true;
      }
    }
    return false;
  }

  @Override
  public boolean updateUserInfo(SubjectDto dto) {
    // 判断密码是否为空如果不为空则更新
    Subject subject = subjectMapper.selectSubjectByUserInfoId(dto.getId());
    if (!subject.getPassword().equals(dto.getPassWord())) {
      String password = encoder.encode(dto.getPassWord());
      subject.setPassword(password);
      subject.setSalt(password.substring(6).substring(0, password.substring(6).indexOf(".")));
    }
    subject.setUpdateTime(timeFormat(System.currentTimeMillis()));
    subject.setSubjectName(dto.getSubjectName());
    // 认证主体更新
    if (subjectMapper.updateById(subject) > 0) {
      // 从前端取出角色id的字符串拼接
      if (dto.getRoleNameIds() != null) {
        QueryWrapper<SubjectRoleMapping> wrapper = new QueryWrapper<>();
        wrapper.eq("subject_id", subject.getId());
        subjectRoleMappingMapper.delete(wrapper);
        String roleNameIds = dto.getRoleNameIds();
        String[] split = roleNameIds.split(",");
        // 删除原来的id及关联表并重新插入
        for (String role : split) {
          SubjectRoleMapping subjectRoleMapping = new SubjectRoleMapping();
          subjectRoleMapping.setSubjectId(subject.getId());
          subjectRoleMapping.setRoleId(Long.parseLong(role));
          subjectRoleMappingMapper.insert(subjectRoleMapping);
        }
      }
    }
    UserInfo userInfo =
        new UserInfo()
            .setId(dto.getId())
            .setUsername(dto.getUsername())
            .setGender(dto.getGender())
            .setWordNum(dto.getWordNum())
            .setPosition(dto.getPosition())
            .setRemark(dto.getRemark())
            .setPhoneNum(dto.getPhoneNum())
            .setUpdateTime(timeFormat(System.currentTimeMillis()));
    // 用户表更新
    if (userInfoMapper.updateById(userInfo) > 0) {
      // 根据前端字符串取出id数组
      if (dto.getDepartmentIds() != null) {
        String departmentIds = dto.getDepartmentIds();
        String[] split = departmentIds.split(",");
        QueryWrapper<DepartmentUserInfoMapping> wrapper = new QueryWrapper<>();
        wrapper.eq("user_info_id", userInfo.getId());
        departmentUserInfoMappingMapper.delete(wrapper);
        // 删除原来的部门及关联表并插入
        for (String s : split) {
          DepartmentUserInfoMapping departmentUserInfoMapping = new DepartmentUserInfoMapping();
          departmentUserInfoMapping.setUserInfoId(userInfo.getId());
          departmentUserInfoMapping.setDepartmentId(Long.parseLong(s));
          departmentUserInfoMappingMapper.insert(departmentUserInfoMapping);
        }
      }
    }
    return true;
  }

  // 逻辑删除
  @Override
  public int deleteUserInfo(Long id) {
    Subject subject = subjectMapper.selectSubjectByUserInfoId(id);
    subject.setEnabled(false);
    QueryWrapper<DepartmentUserInfoMapping> queryWrapper = new QueryWrapper<>();
    QueryWrapper<DepartmentUserInfoMapping> user_info_id = queryWrapper.eq("user_info_id", id);
    List<DepartmentUserInfoMapping> departmentUserInfoMappings =
        departmentUserInfoMappingMapper.selectList(user_info_id);
    if (!Objects.isNull(departmentUserInfoMappings)) {
      for (DepartmentUserInfoMapping departmentUserInfoMapping : departmentUserInfoMappings) {
        departmentUserInfoMappingMapper.deleteById(departmentUserInfoMapping);
      }
    }
    return subjectMapper.updateById(subject);
    /* QueryWrapper<DepartmentUserInfoMapping> queryWrapper = new QueryWrapper<>();
    QueryWrapper<DepartmentUserInfoMapping> user_info_id = queryWrapper.eq("user_info_id", id);
    List<DepartmentUserInfoMapping> departmentUserInfoMappings = departmentUserInfoMappingMapper.selectList(user_info_id);
    if (!Objects.isNull(departmentUserInfoMappings)){
        for (DepartmentUserInfoMapping departmentUserInfoMapping : departmentUserInfoMappings) {
            departmentUserInfoMappingMapper.deleteById(departmentUserInfoMapping);
        }
    }
    QueryWrapper<SubjectRoleMapping> roleMappingQueryWrapper = new QueryWrapper<>();
    QueryWrapper<SubjectRoleMapping> subjectQueryWrapper = roleMappingQueryWrapper.eq("subject_id", subjectId);
    List<SubjectRoleMapping> subjectRoleMappings = subjectRoleMappingMapper.selectList(subjectQueryWrapper);
    if (!Objects.isNull(subjectRoleMappings)) {
        for (SubjectRoleMapping subjectRoleMapping : subjectRoleMappings) {
            subjectRoleMappingMapper.deleteById(subjectRoleMappingMapper.deleteById(subjectRoleMapping));
        }
    }
    QueryWrapper<SubjectUserInfoMapping> wrapper = new QueryWrapper<>();
    QueryWrapper<SubjectUserInfoMapping> subject_id = wrapper.eq("subject_id", subjectId );
    if (subjectUserInfoMappingMapper.delete(subject_id)>0) {
        if (subjectMapper.deleteById(subjectId)>0) {
            return userInfoMapper.deleteById(id);
        }
    }
    return 0;*/
  }
}
